package com.hyy.nio.c2;

import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

@Slf4j
public class WriteServer {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){

                SelectionKey key = iterator.next();
                iterator.remove();
                if(key.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    //也可以直接用ssc
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    SelectionKey scKey = sc.register(selector,0,null);
                    scKey.interestOps(SelectionKey.OP_READ);
                    //1、向客户端发送大量数据
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < 5000000; i++) {
                        sb.append("a");
                    }

                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());

                    //2、返回值代表写入的字节数
                    int write = sc.write(buffer);
                    log.debug("write --- {} ",write);

                    //3、如果还有剩余内容未写，则关注可写时间
                    if(buffer.hasRemaining()){
                        //4、注册可写事件
                        scKey.interestOps(scKey.interestOps()+SelectionKey.OP_WRITE);
                        //5、将未写完的byteBuffer挂到scKey上
                        scKey.attach(buffer);
                    }
                }else if(key.isWritable()){
                    ByteBuffer buffer  = (ByteBuffer) key.attachment();
                    SocketChannel channel = (SocketChannel) key.channel();
                    int write = channel.write(buffer);
                    log.debug("write --- {} ",write);
                    //6、清理操作
                    if(!buffer.hasRemaining()){
                        key.attach(null);//内容写完了，清除buffer
                        key.interestOps(key.interestOps()-SelectionKey.OP_WRITE);//不需要关注可写事件
                    }
                }


            }
        }
    }
}
